﻿<script>
    function ShowResource(haveItem) {
        var id = $('#ddlProjOperExpId').val();
        if (haveItem && id != '' && id != null) {
            $("div #Resource").slideDown(function () {
                var id2 = $("#lblResItemId").val();
                if (id2 != '' && id2 != null) {
                    $("div #Amount").slideDown();
                }
                else {
                    $("div #Amount").slideUp();
                }
            });
            if (haveItem.toLowerCase() == "false") {
                $("div #Resource").slideUp(function () {
                    $("div #Amount").slideDown();
                });
            }
        }
        else if (!haveItem && id != '' && id != null) {
            $("div #Resource").slideUp(function () {
                $("div #Amount").slideDown();
            });
        }
        else {
            $("div #Resource").slideUp(function () {
                $("div #Amount").slideUp();
            });
        }
    }

    $("form").submit(function (e) {
        e.preventDefault();
        var currentForm = this;
        bootbox.confirm(function (result) {
            if (result) {
                currentForm.submit();
            }
        });
    });
    $(function () {

        //fadeStatusText("กำลังโหลดครั้งแรก");
        // คืนค่าโครงการที่เลือกใน Item อื่นๆ เพราะยูซเซอร์ไม่อยากเลือกโครงการใหม่ทุกครั้งที่เพิ่ม Item
        @{
        var ModelPrePurchase = (PrePurchaseRequest)ViewBag.ModelPrePurchase;
        int oldProjOperid = 0;
        int oldProjOperSelectedId = ViewBag.ProjOperId ?? 0;
        if (ModelPrePurchase != null)
        {
            var s = new KPIS.GERP.WEB.GIMS.PrePurchaseRequestItemService.PrePurchaseRequestItemServiceClient();
            var sp = new KPIS.GERP.WEB.GIMS.ProjectOperationService.ProjectOperationServiceClient();
            var items = s.Select(new PrePurchaseRequestItem { PprId = ModelPrePurchase.PprId },
                new[] { "ProjectOperationExpense" });
            PrePurchaseRequestItem lastPprItem = items.OrderByDescending(o=>o.PprItemId).FirstOrDefault();
            if (lastPprItem != null &&
                lastPprItem.ProjOperExpId.HasValue &&
                lastPprItem.ProjectOperationExpense != null  &&
                lastPprItem.ProjectOperationExpense.ProjOperId.HasValue &&
                lastPprItem.ProjectOperationExpense.ProjOperId.Value != 0)
            {
                oldProjOperid = lastPprItem.ProjectOperationExpense.ProjOperId.Value;
                @:    $("#ddlProjOperId").val(@oldProjOperid);
                        <text>
        if ($("#ddlProjOperId").val() == '' && ("@oldProjOperSelectedId" != "0")) {
                        // alert("ท่านไม่มีสิทธิ์แก้ไขรายการพัสดุภายใต้โครงการที่เลือกนี้ได้");
                    }

                </text>
            }
        }
    }
        var resSubGrpIdOld = $('#ddlResSubGrpId').val();
        var resItemIdOld = $('#ddlResItemId').val();
        var descrOld = $("#lblDescr").val();
        var qtyOld = $("#lblQty").val();
        var stdPriceOld = $("#lblStdPrice").val();
        var priceOld = $("#lblPrice").val();
        var amountOld = $("#lblAmount").val();

        var f1 = function () {
            var price = $("#lblPrice").val();
            var qty = $("#lblQty").val();
            var lblAmount = $("#lblAmount");
            // alert("323 price: " + price + ":qty " + qty + ": lblAmount" + lblAmount);

            if (price == "") {
                price = 0;
            }

            if (qty == "") {
                qty = 0;
            }
            var amountComma = addCommas(price * qty);

            lblAmount.val(amountComma);
        };

        var f2 = function () {
            var price = $("#lblPrice").val();
            var qty = $("#lblQty").val();
            var lblAmount = $("#lblAmount");
            // alert("3 2 price: " + price + ":qty " + qty + ": lblAmount" + lblAmount);

            if (price == "") {
                price = 0;
            }

            if (qty == "") {
                qty = 0;
            }

            lblAmount.val(addCommas(price * qty));
            $("#lblQty").val(addCommasOnly(qty));
        };

        @* #1 Load Project Oper Dropdown - #1 โหลดอนุมัติโครงการ*@
        $("#ddlProjOperId").change(function () {
            var id = $('#ddlProjOperId').val();
            var projExpId = $('#ddlProjOperExpId').val();
            if (id != null) {
                $('#ddlResItemId').val('');
                $('#ddlProjOperExpId').empty();
                if (id != '') {
                    fadeStatusText("กำลังโหลดจากอนุมัติโครงการ", false);
                    $.getJSON('@Url.Action("GetProjectOperationExpense")/' + id,
                        function (data) {
                            var selected = " selected = 'selected'";
                            $.each(data, function (i, result) {
                                var text = "<option value='" + result.Value + "' " +
                                    (projExpId == result.Value ? selected : "") + ">" + result.Text + "</option>";
                                $('#ddlProjOperExpId').append(text);
                            });
                        }).always(function () {
                            fadeStatusText("โหลดจากอนุมัติโครงการเสร็จ", true);
                            $('#ddlProjOperExpId').trigger('change');
                        });
                } else {
                    $("div #Resource").hide("slow");
                    $("div #Amount").hide("slow");
                    $("div .loading").hide("slow");
                }
            }
        }).trigger('change');

        @* #2 Load Project Oper Expense Dropdown - #2 โหลดคชจโครงการ ไม่ต้อง Trigger*@
        $('#ddlProjOperExpId').change(function () {
            var id = $('#ddlProjOperExpId').val();
            if (id != null) {
                $('#lblResItemId').val('');

                if (id == "") {
                    $("div #Resource").hide("slow");
                    $("div #Amount").hide("slow");
                } else {
                    var lblResItemId = $('#lblResItemId');
                    var lblResItemName = $('#lblResItemName');
                    var lblResSubGrpName = $('#lblResSubGrpName');
                    var lblResGrpName = $('#lblResGrpName');
                    var lblResTypeName = $('#lblResTypeName');
                    var ddlResGrpId = $('#ddlResGrpId_chzn');
                    var ddlResSubGrpId = $('#ddlResSubGrpId_chzn');
                    var ddlResItemId = $('#ddlResItemId');

                    fadeStatusText("กำลังโหลดประเภทวัสดุ", false);
                    $.getJSON('@Url.Action("GetResourceTypeInfo")?ProjOperExpId=' + id, function (data) {
                        if (data.ProjectExpense != undefined) {
                            lblResItemId.val(data.ProjectExpense.ResItemId);
                            lblResItemName.val(data.ProjectExpense.MasResourceItem.Name);

                            if (data.ProjectExpense == undefined) alert('ProjectExpense is undefined');
                            if (data.ProjectExpense.MasResourceItem == undefined) alert('MasResourceItem is undefined');
                            if (data.ProjectExpense.MasResourceItem.MasResourceSubGroup == undefined) alert('MasResourceSubGroup is undefined');
                            if (data.ProjectExpense.MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType == undefined) alert('MasResourceType is undefined');
                            lblResSubGrpName.val(data.ProjectExpense.MasResourceItem.MasResourceSubGroup.Name);
                            lblResGrpName.val(data.ProjectExpense.MasResourceItem.MasResourceSubGroup.MasResourceGroup.Name);
                            lblResTypeName.val(data.ProjectExpense.MasResourceItem.MasResourceSubGroup.MasResourceGroup.MasResourceType.Name);

                            $("#lblDescr").val(data.Descr);
                            $("#lblUnitName").val(data.ProjectExpense.MasResourceItem.MasUnit.Name);
                            $("#lblStdPrice").val(addCommas(data.ProjectExpense.MasResourceItem.StdPrice));

                            $("#lblPrice").val(addCommas(data.UnitPrice));
                            // alert('2131# ' + $("#lblPrice").val());
                            $("#lblQty").val(data.UnitQty);
                            $("#lblAmount").val(addCommas(data.Amount));

                            $('#lblResItemName').show();
                            $('#lblResSubGrpName').show();
                            $('#lblResGrpName').show();
                            $('#ddlResGrpId_chzn').hide();
                            $('#ddlResSubGrpId_chzn').hide();
                            $('#ddlResItemId').hide();
                            ShowResource($('input[name=HaveItem]:checked').val());
                            $("div #Amount").show("slow");
                        } else {

                            var resGrpIdOld = $('#ddlResGrpId').val();
                            lblResTypeName.val(data.Name);
                            $('#ddlResSubGrpId').empty();
                            $('#ddlResItemId').empty();
                            $("#ddlResSubGrpId").trigger("liszt:updated");//update list

                            $.getJSON('@Url.Action("GetResourceGroupList")?ResTypeId=1', function (data) {// hardcode
                                $('#ddlResGrpId').empty();
                                var items = '';
                                var selected = " selected = 'selected' ";
                                $.each(data, function (i, result) {
                                    var text = "<option value='" + result.Value + "' " +
                                        (resGrpIdOld == result.Value ? selected : "") + ">" + result.Text + "</option>";
                                    $('#ddlResGrpId').append(text);
                                });

                                $("#ddlResGrpId").trigger("liszt:updated");//update list
                            });

                            $("#lblDescr").val('');
                            $("#lblUnitName").val('');
                            $("#lblStdPrice").val(addCommas('0'));
                            $("#lblPrice").val(addCommas('0'));
                            // alert('123129# ' + $("#lblPrice").val());
                            $("#lblQty").val('0');
                            $("#lblAmount").val(addCommas('0'));

                            lblResItemName.hide();
                            lblResSubGrpName.hide();
                            lblResGrpName.hide();

                            ddlResGrpId.show();
                            ddlResSubGrpId.show();
                            ddlResItemId.show();
                            ShowResource($('input[name=HaveItem]:checked').val());
                        }
                    }).always(function () {
                        fadeStatusText("โหลดประเภทวัสดุเสร็จ", true);
                        // firsttime
                        if ($('input[name=HaveItem]:checked').val().toLowerCase() == "false" &&
                            descrOld != "" && qtyOld != "" && stdPriceOld != "" && priceOld != "" && amountOld != "") {
                            $("#lblPrice").off('change');
                            $("#lblQty").off('change');
                            $("#lblDescr").val(descrOld);
                            $("#lblQty").val(qtyOld);
                            $("#lblPrice").val(priceOld);
                            // alert('9213912# ' + $("#lblPrice").val());
                            $("#lblStdPrice").val(stdPriceOld);
                            $("#lblAmount").val(amountOld);
                            $("#lblPrice").on('change', null, f1);
                            $("#lblQty").on('change', null, f2);
                            // alert('21923# ' + $("#lblPrice").val());

                            descrOld = qtyOld = stdPriceOld = priceOld = amountOld = "";
                        }
                        $('#ddlResGrpId').trigger('change');
                    });
                }
            }
        });

        $("#ddlResGrpId").change(function () {
            var id = $('#ddlResGrpId').val();

            if (id != null) {

                if (id != '') {
                    fadeStatusText("กำลังโหลดหมวดพัสดุ", false);
                    $.getJSON('@Url.Action("GetResourceSubGroupList")?ResGrpId=' + id, function (data) {
                        $('#ddlResSubGrpId').empty();
                        $('#ddlResItemId').empty();
                        var items = '';
                        var selected = " selected = 'selected' ";
                        $.each(data, function (i, result) {
                            var text = "<option value='" + result.Value + "' " +
                                (resSubGrpIdOld == result.Value ? selected : "")
                                + ">" + result.Text + "</option>";
                            $('#ddlResSubGrpId').append(text);
                        });
                        resSubGrpIdOld = '';
                        $("#ddlResSubGrpId").trigger("liszt:updated"); //update list
                    }).always(function () {
                        fadeStatusText("โหลดหมวดพัสดุเสร็จ", true);
                        $('#ddlResSubGrpId').trigger('change');
                    });
                } else {
                    $('#ddlResItemId').empty();
                    $("div #Amount").hide("slow");
                }
            }
        });

        $("#ddlResSubGrpId").change(function () {
            var id = $('#ddlResSubGrpId').val();

            if (id != null) {
                if (id != '') {
                    fadeStatusText("กำลังโหลดกลุ่มพัสดุ", false);
                    $.getJSON('@Url.Action("GetResourceItemList")?ResSubGrpId=' + id, function (data) {
                        $('#ddlResItemId').empty();
                        var items = '';
                        var selected = " selected = 'selected' ";
                        $.each(data, function (i, result) {
                            var text = "<option value='" + result.Value + "' " +
                                (resItemIdOld == result.Value ? selected : "")
                                + ">" + result.Text + "</option>";
                            $('#ddlResItemId').append(text);
                        });
                        resItemIdOld = '';
                    }).always(function () {
                        fadeStatusText("โหลดกลุ่มพัสดุเสร็จ", true);
                        $('#ddlResItemId').trigger('change');
                    });
                } else {
                    $("div #Amount").hide("slow");
                }
            }
        });

        $("#ddlResItemId").change(function () {
            var id = $('#ddlResItemId').val();
            if (id != null) {
                if (id != '') {
                    $("#lblResItemId").val(id);
                    fadeStatusText("กำลังโหลดรายการพัสดุ", false);
                    $.getJSON('@Url.Action("GetResourceItemInfo")/' + id, function (data) {
                        $("#lblUnitName").val(data.MasUnit != null ? data.MasUnit.Name : "หน่วย");
                        $("#lblStdPrice").val(addCommas(data.StdPrice));
                        $("#lblPrice").val(addCommas(data.StdPrice));
                        // alert('1219912#  ' + $("#lblPrice").val());
                        $("div #Amount").show("slow");

                        // firsttime
                        if (descrOld != "" && qtyOld != "" && stdPriceOld != "" && priceOld != "" && amountOld != "") {
                            $("#lblPrice").off('change');
                            $("#lblQty").off('change');
                            $("#lblDescr").val(descrOld);
                            $("#lblQty").val(qtyOld);
                            $("#lblPrice").val(priceOld);
                            // alert('9213912# ' + $("#lblPrice").val());
                            $("#lblStdPrice").val(stdPriceOld);
                            $("#lblAmount").val(amountOld);
                            $("#lblPrice").on('change', null, f1);
                            $("#lblQty").on('change', null, f2);
                            // alert('21923# ' + $("#lblPrice").val());

                            descrOld = qtyOld = stdPriceOld = priceOld = amountOld = "";
                        }
                    }).always(function () {
                        fadeStatusText("โหลดรายการพัสดุเสร็จ", true);
                        $('#lblPrice').trigger('change');
                        $('#lblQty').trigger('change');
                    });


                } else {
                    $("div #Amount").hide("slow");
                }
            }
        });
        @* Loading price calculate *@
        $("#lblPrice").change(f1);

        @* Loading Qty calculate *@
        $("#lblQty").change(f2);
    });

    var lastText = '';
    function fadeStatusText(text, fadeOut) {
        // แสดงข้อความสถานะที่ด้านล่างของฟอร์ม แล้วหายไป
        if (!fadeOut) {
            $("#loadingPanel").fadeIn(100);
        }
        if (text.length > 0) { lastText = text; }
        $("#textloding").fadeOut(100, function () {
            var newText = "" + (text.length > 0 ? text : ' no (' + lastText + ')');
            $(this).text(newText).fadeIn(100);
        });
        if (fadeOut) {
            $("#loadingPanel").fadeOut(100);
        }
    }

</script>